package cn.org.itool.ws.framework.listener;

import cn.org.itool.ws.framework.utils.ChannelGroupUtil;
import cn.org.itool.ws.framework.ws.WsServer;
import cn.org.itool.ws.pojo.BroadcastMessage;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

@Log4j2
public class BroadcastMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {

        String channel = new String(message.getChannel());
        System.out.println("Received message: from channel: " + channel);
        BroadcastMessage json = null;
        try {
            json = WsServer.OBJECT_MAPPER.readValue(message.getBody(), BroadcastMessage.class);

            // 消息转发
            ChannelGroupUtil.writeAndFlush(json.getGroupName(), json.getIncludeUserIds(), json.getIgnoreUserIds(), json.getBody());
        } catch (Exception e) {
            log.error("onMessage error : ", e);
            throw new RuntimeException(e);
        }
    }
}
